package com.hnl.action.talent;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Vector;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hnl.core.HNLPageDispatch;
import com.hnl.core.aware.HNLAuthAware;
import com.hnl.core.aware.HNLTalentAware;
import com.hnl.core.aware.MiscTypeAware;
import com.hnl.dao.DAOException;
import com.hnl.dao.HNLDAOFactory;
import com.hnl.dao.TalentDAO;
import com.hnl.to.Talent;
import com.hnl.util.JSONResponseUtil;

@SuppressWarnings("serial")
public class ReferralAutocompleteLoader extends HttpServlet implements
		HNLAuthAware, HNLTalentAware, MiscTypeAware, HNLPageDispatch {
	public static final Logger LOG = LoggerFactory
			.getLogger(AddReferralInfo.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		PrintWriter writer = resp.getWriter();
		try {
			String term = req.getParameter("term");

			TalentDAO talentDAO = HNLDAOFactory.getDAOFactory(
					HNLDAOFactory.HNLDAOFACTORY).getTalentDAO();
			Collection<Talent> talentColletion = talentDAO
					.loadAllTalentLikeTerm(term);

			Collection<IdValuePair> itemColletion = new Vector<IdValuePair>();

			for (Talent talent : talentColletion) {
				IdValuePair item = new IdValuePair();
				item.Id = talent.getTalentId();
				item.value = talent.geteFirstname() + " "
						+ talent.geteLastname();
				if ((talent.getcFirstname() != null && talent.getcFirstname()
						.length() > 0)
						|| (talent.getcLastname() != null && talent
								.getcLastname().length() > 0)) {
					item.value += "(" + talent.getcLastname()
							+ talent.getcFirstname() + ")";
				}
				itemColletion.add(item);
			}
			writer.println(JSONResponseUtil.getJSONObjectString(itemColletion));

		} catch (DAOException e) {
			LOG.error("Error to add talent.", e);
		} finally {
			writer.close();
		}

	}

	private class IdValuePair {
		Integer Id;
		String value;
	}
}
